/**
 * 退货出库管理初始化
 */
var GoodsReturn = {
    id: "ReturnListTable",	//表格id
    seItem: null,		//选中的条目
    returnTableData: {},
    table: null,
    layerIndex: -1
};

/**
 * 初始化退货商品表格
 */
GoodsReturn.initColumn = function () {
    return [
        {field: 'selectItem', radio: true},
        {title: '退货商品ID', field: 'goodsId', visible: false, align: 'center', valign: 'middle'},
        {title: '退货数量', field: 'goodsNum', visible: true, align: 'center', valign: 'middle'},
        {title: '商品编码', field: 'goodsCode', visible: true, align: 'center', valign: 'middle'},
        {title: '商品名称', field: 'goodsName', visible: true, align: 'center', valign: 'middle'},
        {title: '商品型号', field: 'goodsModel', visible: true, align: 'center', valign: 'middle'},
        {title: '商品单价', field: 'goodsUnit', visible: true, align: 'center', valign: 'middle'},
        {title: '退货价格', field: 'goodsReturnPrice', visible: true, align: 'center', valign: 'middle'},
        {title: '退货总价', field: 'totalPrice', visible: true, align: 'center', valign: 'middle'},
        {title: '退货清单ID', field: 'returnGoodsListId', visible: true, align: 'center', valign: 'middle'},
        {title: '创建者', field: 'createBy', visible: false, align: 'center', valign: 'middle'},
        {title: '创建时间', field: 'createDate', visible: true, align: 'center', valign: 'middle'},
        {title: '更新者', field: 'updateBy', visible: false, align: 'center', valign: 'middle'},
        {title: '更新时间', field: 'updateDate', visible: false, align: 'center', valign: 'middle'},
        {title: '备注信息', field: 'remarks', visible: true, align: 'center', valign: 'middle'},
        {title: '删除标记（0：正常；1：删除）', field: 'delFlag', visible: false, align: 'center', valign: 'middle'}
    ];
};

/**
 * 清除数据
 */
GoodsReturn.clearData = function () {
    this.returnTableData = {};
}
/**
 * 清除dom显示数据
 */
GoodsReturn.clearDom = function () {
    this
        .setDomVal('id')
        .setDomVal('amountPaid')
        .setDomVal('amountPayable')
        .setDomVal('returnOrderNumber')
        .setDomVal('payState')
        .setDomVal('createBy')
        .setDomVal('createDate')
        .setDomVal('updateBy')
        .setDomVal('updateDate')
        .setDomVal('remarks')
        .setDomVal('delFlag')
        .setDomVal('supplierId');
}

/**
 * 收集数据
 */
GoodsReturn.collectData = function () {
    this
        .set('id')
        .set('amountPaid')
        .set('amountPayable')
        .set('returnOrderNumber')
        .set('payState')
        .set('createBy')
        .set('createDate')
        .set('updateBy')
        .set('updateDate')
        .set('remarks')
        .set('delFlag')
        .set('supplierId');
}

/**
 * 设置对话框中的数据
 *
 * @param key 数据的名称
 * @param val 数据的具体值
 */
GoodsReturn.set = function (key, val) {
    this.returnTableData[key] = (typeof val === "undefined") ? $("#" + key).val() : val;
    return this;
}

/**
 * 设置dom中的数据
 *
 * @param key 数据的名称
 * @param val 数据的具体值
 */
GoodsReturn.setDomVal = function (key, val) {
    (typeof val === "undefined") ? $("#" + key).val('') : $("#" + key).val(val);
    return this;
}

/**
 * 设置对话框中的数据
 *
 * @param key 数据的名称
 * @param val 数据的具体值
 */
GoodsReturn.get = function (key) {
    return $("#" + key).val();
}


/**
 * 检查是否选中
 */
GoodsReturn.check = function () {
    var selected = $('#' + this.id).bootstrapTable('getSelections');
    if (selected.length === 0) {
        Feng.info("请先选中表格中的某一记录！");
        return false;
    } else {
        GoodsReturn.seItem = selected[0];
        return true;
    }
};

/**
 * 点击添加退货出库
 */
GoodsReturn.openAddGoodsReturn = function () {
    var index = layer.open({
        type: 2,
        title: '退货出库',
        area: ['800px', '420px'], //宽高
        fix: false, //不固定
        maxmin: true,
        content: Feng.ctxPath + '/goodsReturn/goodsReturn_add'
    });
    this.layerIndex = index;
};

/**
 * 删除退货出库
 */
GoodsReturn.delete = function () {
    if (this.check()) {
        var selected = this.table.btInstance.bootstrapTable('getSelections');
        console.log(selected[0].goodsId);
        this.table.btInstance.bootstrapTable('removeByUniqueId', selected[0].goodsId);
    }
};

/**
 * 查询供应商
 */
GoodsReturn.selectSupplier = function () {
    //查找供应商下拉框
    var ajax = new $ax(Feng.ctxPath + "/managerSupplier/list", function (data) {
        $.each(data, function (index, supplier) {
            var supplierId = supplier['id'];
            var supplierName = supplier['supplierName'];
            $("#supplierId").html("<option value='" + supplierId + "'>" + supplierName + "</option>");
        })
    }, function (data) {
        Feng.error("获取供应商失败!" + data.responseJOSN.message + "!");
    });
    ajax.start();
}

/**
 * 是否支付下拉框
 */
GoodsReturn.isPaySelect = function () {
    $("#payState").html("<option value='1'>已支付</option>" +
        "<option value='0'>未支付</option>")
}


/**
 * 保存前检查数据
 */
GoodsReturn.checkData = function () {
    var data = GoodsReturn.table.btInstance.bootstrapTable('getData', true);

    if ('' === data || typeof data === 'undefined' || data.length === 0) {
        Feng.info('请先添加商品！');
        return false;
    }

    var supplier = $("#supplierId option:selected").val();
    if ('' === supplier || typeof supplier === 'undefined') {
        Feng.info("请选择供应商！");
        return false;
    }

    var amountPaid = $("#amountPaid").val();
    if ('' === amountPaid || typeof amountPaid === 'undefined') {
        Feng.info('请输入实付金额!');
        return false;
    }

    var amountPayable = $("#amountPayable").val();
    if ('' === amountPayable || typeof amountPayable === 'undefined') {
        Feng.info("请输入应付金额!");
        return false;
    }

    var createDate = $("#createDate").val();
    if ('' === createDate || typeof createDate === 'undefined') {
        Feng.info("请选择订单日期!");
        return false;
    }

    var state = $("#payState option:selected").val();
    if ('' === state || typeof state === 'undefined') {
        Feng.info("请选择是否支付!");
        return false;
    }

    var orderNumber = $("#returnOrderNumber").text();
    if ('' === orderNumber || typeof orderNumber === 'undefined') {
        Feng.info("订单号为空，请刷新页面重新提交!");
        return false;
    }

    return true;
}

/**
 * 选中商品后计算出价格并赋值
 */
GoodsReturn.calculateTotalPrice = function (cTotalPrice) {
    var cAmountPaid = $("#amountPaid").val();
    var cAmountPayable = $("#amountPayable").val();
    if (cAmountPaid === '' || cAmountPayable === '') {
        $("#amountPaid").val(cTotalPrice);
        $("#amountPayable").val(cTotalPrice);
    } else {
        var amountPaid = parseFloat(cAmountPaid);
        var amountPayable = parseFloat(cAmountPayable);
        //累加价格
        $("#amountPaid").val(cTotalPrice + amountPaid);
        $("#amountPayable").val(cTotalPrice + amountPayable);
    }
}

/**
 * 订单保存
 */
GoodsReturn.save = function () {
    if (this.checkData()) {
        //清除数据
        this.clearData();
        //获取form数据
        this.collectData();
        var ajax = new $ax(Feng.ctxPath + "/goodsReturn/add", function (data) {
            Feng.success(data.message);
            //清除表单
            GoodsReturn.clearData();
            //清除dom数据显示
            GoodsReturn.clearDom();
            //清除表格数据
            GoodsReturn.table.btInstance.bootstrapTable('removeAll');
            //输出
            console.log('新退货单号：', data.result);
            //重新赋值单号
            $("#returnOrderNumber").text(data.result);
        }, function (data) {
            Feng.error("获取供应商失败!" + data.responseJOSN.message + "!");
        });
        //获取单据号码
        this.returnTableData['returnOrderNumber'] = $('#returnOrderNumber').text();
        //获取添加的表格数据
        this.returnTableData['returnGoodsList'] = this.table.btInstance.bootstrapTable('getData', true);
        //请求数据
        var requestData = JSON.stringify(this.returnTableData);

        console.log('请求数据->', requestData);

        //设置为请求数据为json类型
        ajax.setContentType('application/json');
        ajax.setData(requestData);
        ajax.start();
    }
}


$(function () {
    var defaultColunms = GoodsReturn.initColumn();
    var table = new BSTable(GoodsReturn.id, "", defaultColunms);
    table.setPaginationType("client");
    table.setShowRefresh(false);
    table.setShowColumns(false);
    table.setUniqueId("goodsId");
    GoodsReturn.table = table.init();

    //初始化下拉框
    GoodsReturn.isPaySelect();
    GoodsReturn.selectSupplier();
});
